﻿using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace FlyingEye.DeviceClients
{
    public class JwtTokenGenerator
    {
        /// <summary>
        /// 生成包含 resourceId 的 JWT Token
        /// </summary>
        /// <param name="secretKey">密钥（建议长度至少 32 字符）</param>
        /// <param name="issuer">签发者</param>
        /// <param name="audience">接收者</param>
        /// <param name="resourceId">需要存储的资源标识符</param>
        public static string GenerateToken(
            string secretKey,
            string issuer,
            string audience,
            string resourceId)
        {
            // 1. 构建声明集
            var claims = new[]
            {
            new Claim("resourceId", resourceId), // 核心参数存储
            new Claim(JwtRegisteredClaimNames.Sub, "user_auth"), // 标准声明示例
            new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()) // 唯一标识
        };

            // 2. 创建签名凭证
            var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));
            var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

            // 3. 配置 Token 描述符
            var tokenDescriptor = new JwtSecurityToken(
                issuer: issuer,
                audience: audience,
                claims: claims,
                signingCredentials: credentials,
                expires: null // 这里不设置过期时间
            );

            // 4. 生成 Token 字符串
            return new JwtSecurityTokenHandler().WriteToken(tokenDescriptor);
        }
    }
}